import { Injectable } from '@angular/core';
// import {UserAuthService} from '@core/services/user-auth.service';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { format } from 'date-fns';


@Injectable({
  providedIn: 'root',
})
export class PurchaseService {
  private pt_company: any[];

  constructor(private apiService: ApiService,
              private msg: ApesMessageService) {
  }

  /** 获取公司 **/
  public getCompany(permitId: string) {
    // 获取所有公司
    this.apiService.post('cm.company.findAllCompany', {}).subscribe((data) => {
      if (data) { this.pt_company = data['pt_company'] }
    });
    return new Promise(resolve => {
      setTimeout(()=>{
        this.apiService.post('aut.localPermit.findOneForUi', { 'body': JSON.stringify({ id: permitId }) })
          .subscribe(body => {
            let localPermit: any[];
            const companyClone: any[] = [];
            if (JSON.stringify(body.permitPurposeSearch.pt_company) === '[]') {
              localPermit = this.pt_company;
            } else {
              localPermit = body.permitPurposeSearch.pt_company;
            }
            for (const item of localPermit) {
              if (item.operation === '直营' || item.operation === '合伙人' || item.operation === '赋能店' || item.operation === '直营子公司') {
                companyClone.push(item);
              }
            }
            resolve(companyClone);
          });
      },1000)

    });
  }

  /** 获取销售组 **/
  public getSaleData() {
    let data = { 'interfaceMethod': 'ipmQueryXszService.queryXszData', 'pdata': { 'MJBJ': 0 } };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const saleData = JSON.parse(result.obj);
              resolve(saleData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });

  }

  /** 获取询价区域 **/
  public getInquiryData() {
    let data = { 'interfaceMethod': 'ipmVipService.queryBJZ', 'pdata': {} };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const inquiryData = JSON.parse(result.obj);
              resolve(inquiryData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

  /** 获取门店名称 **/
  public getStoreData(companyList) {
    let data = { 'interfaceMethod': 'ipmVipService.getMDXX', 'pdata': { 'companyId': companyList } };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const storeData = JSON.parse(result.obj);
              resolve(storeData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

  /** 获取供应商 **/
  public getSupplierData() {
    let data = { 'interfaceMethod': 'ipmVipService.getGYSXX', 'pdata': {} };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const supplierData = JSON.parse(result.obj);
              resolve(supplierData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

  /** 获取仓库库区 **/
  public getWarehouseData() {
    let data = { 'interfaceMethod': 'ipmVipService.qryCKKQ', 'pdata': { 'KQID': 1 } };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const warehouseData = JSON.parse(result.obj);
              resolve(warehouseData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

  /** 获取表单grid数据 **/
  public getTablesData(data: any) {
    let rowData = [];
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              let list: any = JSON.parse(result.obj);
              rowData = list.DETAILS;
              rowData = rowData.sort(this.sortarr('HS'));
              if (rowData.length === 0) {
                this.msg.info(`未找到满足条件的数据`);
              }
              resolve(rowData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });

  }

  /** 获取报价组 **/
  public getOfferGroup() {
    let data = { 'interfaceMethod': 'mdmDdxxService.queryDDXXBJZ', 'pdata': {'test':'value'} };
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const inquiryData = JSON.parse(result.obj);
              resolve(inquiryData);
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

  /** 日期相减 **/
  public getTimeChang(d1, d2, times) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      let days = (checkTime - checkTime2) / day;
      if (days <= times) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  /** 日期转换 **/
  public getDate(time: any[], time_ks: string, time_js: string, then) {
    let [first, second] = time;
    if (first) {
      then[time_ks] = first.toISOString().slice(0, 10);
    } else {
      then[time_ks] = null;
    }

    if (second) {
      then[time_js] = second.toISOString().slice(0, 10);
    } else {
      then[time_js] = null;
    }
  }

  /** 时间转换x天x小时x分钟 7.5小时**/
  public toHour(params) {
    return timeChang(params, 7.5);
  }

  /** 时间转换x天x小时x分钟 11小时**/
  public toHours(params) {
    return timeChang(params, 11);
  }

  /** 时间转换x天x小时x分钟 24小时**/
  public toTime(params) {
    return timeChang(params, 24);
  }

  /** 排序 倒序 **/
  private sortarr(key) {
    return function(a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0;
      return b[key] - a[key];
    };
  }

  /** apes-range-picker 选时间快捷方式 数组**/
  public dayChang(value: number) {
      const timesData: any[] = [];
      const todays: any = new Date();
      const endTimes = format(todays, 'YYYY-MM-DD');
      const startTims = format(new Date(todays.getTime() - (value * 24 * 60 * 60 * 1000)), 'YYYY-MM-DD');
      timesData.push(startTims);
      timesData.push(endTimes);
      return timesData;
  }

  /** 调用饼图信息 **/
  public getPie(data: any, title:string) {
    return new Promise(resolve => {
      this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              let list: any = JSON.parse(result.obj);
              if(JSON.stringify(list) !== '[]') {
                resolve(list);
              }else {
                this.msg.error(title + `未找到满足条件的数据`);
              }
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    });
  }

}

/** 时间转换 公用公式 **/
export function timeChang(params: any, hours: number) {
  let data: any;
  if (typeof(params) == 'object') {
    let key = params.colDef.field;
    if (params.data[key]) {
      data = params.data[key];
    } else {
      data = params;
    }
  } else {
    data = params;
  }

  let a = data >= 0 ? '' : '-';
  data = data >= 0 ? data : -data;

  let day = Math.floor(data / (hours * 60));
  let hour = day >= 0
    ? Math.floor((data - (day * (hours * 60))) / 60)
    : Math.floor(data / 60);
  let minute = hour >= 0
    ? Math.floor(data - (day * (hours * 60)) - (hour * 60))
    : data < 0
      ? data
      : Math.floor(data / 60 / hours);

  let time = '';
  if (day > 0) {
    time = a + day + '天' + hour + '小时' + minute + '分钟';
  } else if (hour) {
    time = a + hour + '小时' + minute + '分钟';
  } else if (minute) {
    time = a + minute + '分钟';
  }
  return time;
}



